#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle(tr("Control Host Server"));
    this->setWindowIcon(QIcon(":/images/HostSrv.png"));
    this->setWindowFlags(Qt::WindowMinMaxButtonsHint);
    this->setFixedSize(400, 300);

    createAction();
    createTrayIcon();
    m_trayIcon->show();

    m_pSocketSrv = new FormSocketSrv(this);
    connect(m_pSocketSrv, SIGNAL(sigSrvStateChanged(bool)), this, SLOT(slotSrvStateChanged(bool)));
    m_pSocketSrv->startServer(true);
}

MainWindow::~MainWindow()
{
    delete ui;
    delete m_startAction;
    delete m_showAction;
    delete m_quitAction;
    delete m_trayIcon;
    delete m_trayIconMenu;

    if (m_pSocketSrv != NULL)
    {
        delete m_pSocketSrv;
        m_pSocketSrv = NULL;
    }
}

void MainWindow::createAction()
{
    m_startAction = new QAction(tr("Stop"), this);
    m_showAction = new QAction(tr("Show"), this);
    m_quitAction = new QAction(tr("Quit"), this);

    connect(m_startAction, SIGNAL(triggered()), this, SLOT(slotStartSrv()));
    connect(m_showAction, SIGNAL(triggered()), this, SLOT(slotShow()));
    connect(m_quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}

void MainWindow::createTrayIcon()
{
    m_trayIconMenu = new QMenu(this);
    m_trayIconMenu->addAction(m_startAction);
    m_trayIconMenu->addAction(m_showAction);
    m_trayIconMenu->addAction(m_quitAction);

    m_trayIcon = new QSystemTrayIcon(this);
    m_trayIcon->setIcon(QIcon(":/images/HostSrv.png"));
    m_trayIcon->setToolTip(tr("Control Host Server"));
    connect(m_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(slotIconActivated(QSystemTrayIcon::ActivationReason)));
    m_trayIcon->setContextMenu(m_trayIconMenu);
}

//state: true--Start
//       false--Stop
void MainWindow::slotSrvStateChanged(bool state)
{
    if (state)
    {
        m_startAction->setText(tr("Stop"));
    }
    else
    {
        m_startAction->setText(tr("Start"));
    }
}

void MainWindow::slotStartSrv()
{
    if (m_pSocketSrv != NULL)
    {
        if (m_startAction->text() == tr("Start"))
        {
            m_pSocketSrv->startServer(true);
            m_startAction->setText(tr("Stop"));
        }
        else
        {
            m_pSocketSrv->startServer(false);
            m_startAction->setText(tr("Start"));
        }
    }
}

void MainWindow::slotShow()
{
    this->show();
}

void MainWindow::slotIconActivated(QSystemTrayIcon::ActivationReason reason)
{

    switch (reason) {
    //case QSystemTrayIcon::Trigger:
    case QSystemTrayIcon::DoubleClick:
        this->show();
        break;
    default:
        break;
    }
}
